package com.cqupt.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cqupt.exception.BusinessException;
import com.cqupt.model.pojo.SignRecord;
import com.cqupt.model.vo.ResultCodeEnum;
import com.cqupt.service.SignRecordService;
import com.cqupt.mapper.SignRecordMapper;
import com.cqupt.utils.AuthContextUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.function.Function;


@Service
public class SignRecordServiceImpl extends ServiceImpl<SignRecordMapper, SignRecord>
        implements SignRecordService {

    @Resource
    private SignRecordMapper signRecordMapper;

    @Override
    public List<String> signRecord() {
        Integer userId = AuthContextUtil.get().getId();
        LambdaQueryWrapper<SignRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SignRecord::getUserId, userId);
        List<SignRecord> signRecords = signRecordMapper.selectList(wrapper);
        List<String> list = signRecords.stream().map(new Function<SignRecord, String>() {
            @Override
            public String apply(SignRecord signRecord) {
                return signRecord.getDate();
            }
        }).toList();
        return list;
    }

    @Override
    public void sign(String date) {
        Integer userId = AuthContextUtil.get().getId();
        LambdaQueryWrapper<SignRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SignRecord::getUserId, userId);
        wrapper.eq(SignRecord::getDate, date);
        SignRecord one = signRecordMapper.selectOne(wrapper);
        if (ObjectUtil.isNotNull(one)) {
            throw new BusinessException(ResultCodeEnum.DATA_ERROR);
        }
        SignRecord signRecord = new SignRecord();
        signRecord.setUserId(userId);
        signRecord.setDate(date);
        signRecordMapper.insert(signRecord);
    }
}




